package com.leyou.gateway.task;

import com.leyou.gateway.client.AuthClient;
import com.leyou.gateway.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class AppTokenHolder {

    /**
     * token刷新间隔
     */
    private static final long TOKEN_REFRESH_INTERVAL = 86400000L;

    /**
     * token获取失败后重试的间隔
     */
    private static final long TOKEN_RETRY_INTERVAL = 10000L;

    @Autowired
    private AuthClient authClient;

    @Autowired
    private JwtProperties prop;

    private String token;

    // 每隔24小时去申请一次token
    @Scheduled(fixedDelay = TOKEN_REFRESH_INTERVAL)
    public void loadTokenTask() throws InterruptedException {
        while (true) {
            try {
                // 申请了token
                this.token = authClient.authorization(prop.getApp().getId(), prop.getApp().getSecret());
                log.info("【网关微服务】申请token成功");
                break;
            } catch (Exception e) {
                log.error("【网关微服务】申请token失败：{}", e.getMessage());
            }
            Thread.sleep(TOKEN_RETRY_INTERVAL);
        }
    }

    // 获取token
    public String getToken(){
        return token;
    }

}
